package com.biglead.demo.controller;

import com.biglead.demo.common.PageResult;
import com.biglead.demo.common.R;
import com.biglead.demo.pojo.Order;
import com.biglead.demo.pojo.RequestParams;
import com.biglead.demo.service.OrderService;
import com.biglead.demo.vo.OrderVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author 早起的年轻人
 * @since 2023-03-14
 */
@Api(tags = "订单模块")
@RestController()
@RequestMapping("/orders")
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 下单
     *
     * @param goodsId 商品ID
     * @param userId
     * @return
     */
    @GetMapping("/create/{id}")
    public R createPreOrder(@PathVariable("id") Long goodsId, @RequestHeader Long userId) {
        return orderService.createPreOrder(goodsId, userId);
    }

    /**
     * 查询订单状态与详情
     * 商品-下单入口调用
     *
     * @param sn
     * @return
     */
    @GetMapping("/statues/detail/{sn}")
    public R detailAndStatue(@PathVariable("sn") Long sn) {
        //redis 中查询状态
        Boolean aBoolean = redisTemplate.hasKey("sn:" + sn);
        if (Boolean.FALSE.equals(aBoolean)) {
            return R.error("下单失败");
        }
        String snStatues = redisTemplate.opsForValue().get("sn:" + sn).toString();
        //未下单完
        if (snStatues.equals("doing")) {
            return R.error(202, "处理中");
        }
        //未下单成功
        if (!snStatues.equals("ok")) {
            return R.error(203, snStatues);
        }
        //下单成功 返回订单信息
        OrderVo orderVo = orderService.detailFromSn(sn);
        return R.okData(orderVo);
    }

    /**
     * 查询订单详情
     *
     * @param orderId
     * @return
     */
    @GetMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long orderId) {
        OrderVo orderVo = orderService.detailFromId(orderId);
        return R.okData(orderVo);
    }


    /**
     * 查询用户所有的订单
     */
    @PostMapping("/es/list")
    public PageResult listFromList(@RequestHeader Long userId,
                                   @RequestBody RequestParams params) {
        PageResult pageResult = orderService.listFromList(userId,params);
        return pageResult;
    }
    /**
     * 查询指定订单的详情
     */
    @PostMapping("/es/info/{id}")
    public R orderFromEs(@PathVariable Long id) {
        Order order = orderService.getOrderDetailFromEs(id);
        return R.okData(order);
    }
    /**
     * 更新指定订单的状态
     */
    @PostMapping("/es/update")
    public R updateOrderFromEs(@RequestBody Order order) {
        orderService.updateOrderById(order);
        return R.ok();
    }
}
